package org.jradweb.tools.generator.untils;

import static org.unitils.thirdparty.org.apache.commons.io.IOUtils.closeQuietly;

import java.io.InputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.unitils.dbmaintainer.script.ScriptContentHandle;
import org.unitils.dbmaintainer.script.ScriptParser;
import org.unitils.dbmaintainer.script.impl.DefaultScriptRunner;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class JScriptRunner extends DefaultScriptRunner {

	@Override
	public void execute(ScriptContentHandle scriptContentHandle) {
		Configuration conf = new Configuration();
		conf.setLocale(java.util.Locale.CHINESE);
	    DBScriptTemplateLoader loader=new DBScriptTemplateLoader();
		conf.setTemplateLoader(loader);
		conf.setLocalizedLookup(false);

		Reader scriptContentReader = null;
		try {
			// get content stream
			scriptContentReader = scriptContentHandle.openScriptContentReader();

			// create a parser
			ScriptParser scriptParser = createScriptParser();
			scriptParser.init(configuration, scriptContentReader);
			
			
			InputStream in = Thread.currentThread()
			.getContextClassLoader().getResourceAsStream(
			"database.properties");
			Properties props = new Properties();
			props.load(in);
			//System.out.println("database properties: "+props);
			Map<String,String> map=new HashMap<String,String>();
			for(Object key:props.keySet()){
				map.put((String)key, (String)props.get(key));
			}

			// parse and execute the statements
			String statement;
			while ((statement = scriptParser.getNextStatement()) != null) {
				if (statement != null && statement.trim().length() > 0) {
					String name=loader.putStatement(statement);
					Template t = conf.getTemplate(name);
					StringWriter out = new StringWriter();
					t.process(map, out);
					String newStatement = out.toString();
					sqlHandler.executeUpdateAndCommit(newStatement);
				}

			}
		} catch (java.io.IOException e) {
			throw new DBScriptParameterException(e);
		} catch (TemplateException e) {
			throw new DBScriptParameterException(e);
		} finally {
			closeQuietly(scriptContentReader);
		}
	}

}
